const sketch = document.getElementById('sketch');
const htmlDraft = document.getElementById('htmlCode');
const cssDraft = document.getElementById('cssCode');
const logger = document.getElementById('logger');
const sterilizer = DOMPurify;
const a11y = axe;

function saveSketch() {
  let skt = {html: sterilizer.sanitize(htmlDraft.value), css: cssDraft.value};
  location.hash = encodeURIComponent(window.btoa(JSON.stringify(skt)));
}

function openSketch() {
  if(location.hash.length > 1) {
    let savedSketch = JSON.parse(window.atob(decodeURIComponent(location.hash.substr(1))));
    htmlDraft.value = sterilizer.sanitize(savedSketch.html);
    cssDraft.value = savedSketch.css;
  }
}

function renderSketch() {
  sketch.srcdoc = ("<!DOCTYPE html><html lang='en'><head>" +
                   "<meta charset='utf-8'/><style>" +
                   cssDraft.value +
                   "</style></head><body>" +
                   sterilizer.sanitize(htmlDraft.value) +
                   "<\/body><\/html>");
}

function printA11yResults() {
  a11y.run(sketch.contentWindow.document, function(err, skt) {
    logger.value = "a11y> ";
    skt.violations.map(v => logger.value += JSON.stringify(v, null, 2));
  });
}

window.onload = function() {
  openSketch();
  renderSketch();
  printA11yResults();
};

document.body.oninput = function() {
  renderSketch();
  printA11yResults();
  saveSketch();
};
